<?php
/**
 * 抢购活动管理
 */
namespace Admin\Controller;
use Think\Controller;
use Think\Log;
class PImportController extends Controller
{
    protected $model;
    protected $return;


    public function __construct(){
        header("Access-Control-Allow-Origin: *");
        $this->model = D('PUser');
        $this->return = array('errcode'=>0, 'errmsg'=>'ok');
        if(ACTION_NAME != 'login'){
            $admin = session('rush_admin');
            if (!$admin) {
                $this->ajaxReturn(array('errcode'=>10000,'errmsg'=>'请先登录'));
            }
        }
    }

    public function scoreimport(){
        if(!empty($_FILES)){


            $filename='./Uploads/'.time();
            move_uploaded_file($_FILES["file"]["tmp_name"],$filename);

            $expire=M('PConfig')->where(array('key'=>'import_expire'))->find();
            $expire2=M('PConfig')->where(array('key'=>'task_expire'))->find();

            $model = M("PUser");
            $model->startTrans();
            $handle = fopen($filename, 'r');
            $first=true;
            $update=true;


            while($data = fgetcsv($handle)){

                if(count($data) < 2){
                    continue;
                }
                if($first){
                    $first=false;
                    continue;
                }
                $phone = iconv('gb2312', 'utf-8', $data[0]);
                $phone = trim($phone);
                $scope = intval(trim($data[1]));


                $user=$model->where(array('phone'=>$phone,'is_deleted'=>0))->find();
                if(!$user){
                    continue;
                }
                $record['user_id'] = $user['id'];
                $record['score'] = $scope;
                $record['consume'] = $scope;
                $record['expire_time']=time()+$expire2['value']*3600*24;

                $record['add_time'] = time();
                $record['type'] = 2;
                $scoreRes = M("PScoreRecord")->add($record);

                unset($user);
                if(!$scoreRes){
                    $update = false;
                    break;
                }

            }
            fclose($handle); //关闭指针
            unlink($filename);

            if($update){
                $model->commit();
                $this->ajaxReturn(array('errcode'=>0, 'errmsg'=>'部分用户积分已变更，详情请查看积分记录！'));
            }else{
                $model->rollback();
                $this->ajaxReturn(array('errcode'=>10002, 'errmsg'=>'更新积分失败'));
            }
        }else{
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'请上传文件'));
        }
    }

    public function scoreview(){
        if(!empty($_FILES)){

            $filename='./Uploads/'.time();
            move_uploaded_file($_FILES["file"]["tmp_name"],$filename);

            $expire=M('PConfig')->where(array('key'=>'import_expire'))->find();

            $handle = fopen($filename, 'r');
            $first=true;

            $model = M("PUser");

            $list=array();

            $time=time();

            $records=D("PScoreRecord")->query('select user_id, consume from zsf_p_score_record where is_deleted=0 and consume>0 and expire_time>='.$time.' and type in (1,2,5,6,7)');


            while($data = fgetcsv($handle)){

                if(count($data) < 2){
                    continue;
                }
                if($first){
                    $first=false;
                    continue;
                }
                $phone = iconv('gb2312', 'utf-8', $data[0]);
                $phone = trim($phone);
                $scope = intval(trim($data[1]));


                $user=$model->where(array('phone'=>$phone,'is_deleted'=>0))->find();
                if(!$user){
                    continue;
                }


                $sum=0;
                foreach ($records as $k1 =>$v1){
                    if($v1['user_id']==$user['id']){
                        $sum+=$v1['consume'];
                    }
                }
                $user['score']=$sum;

                $user['new_score']=$scope;
                $user['updated_score']=$sum+$scope;
                array_push($list,$user);

            }
            fclose($handle); //关闭指针
            unlink($filename);

            $page = pagination(count($list), 10000 ,1);
            $array= array('data'=>$list, 'page'=>$page);

            return $this->ajaxReturn(array_merge($this->return, $array));

        }else{
            $page = pagination(0, 10000 ,1);
            $array= array('data'=>array(), 'page'=>$page);
            return $this->ajaxReturn(array_merge($this->return, $array));
        }
    }


    public function amountimport(){
        if(!empty($_FILES)){

            $filename='./Uploads/'.time();
            move_uploaded_file($_FILES["file"]["tmp_name"],$filename);

            $model = M("PUser");
            $model->startTrans();
            $update = true;

            $expire=M('PConfig')->where(array('key'=>'import_expire'))->find();
            $expire2=M('PConfig')->where(array('key'=>'task_expire'))->find();

            $handle = fopen($filename, 'r');
            $first=true;
            while($data = fgetcsv($handle)){

                if(count($data) < 6){
                    continue;
                }
                $name = iconv('gb2312', 'utf-8', $data[0]);
                $name = trim($name);
                $phone = trim($data[1]);
                $account = trim($data[2]);
                $amount = $data[4];
                $taskid=$data[5];
                $task_scope=0;
                if (empty($name)) {
                    continue;
                }

                if($first){
                    $first=false;
                    continue;
                }

                $user = $model->where(array('phone'=>$phone,'account'=>$account))->find();
                if (!$user) {
                    continue;
                }

                if(!empty($taskid)){      //如果任务id不为空，则代表完成了任务
                    $tmpModel=M("PTaskPerson")->where(array('user_id'=>$user['id']))->find();

                    if($tmpModel && intval($tmpModel['finish_time'])<1){

                        //再添加任务的积分，
                        $task_scope=trim($data[6]);

                        $task_scope=intval($task_scope);
                        $taskWhereParam['user_id']=$user['id'];
                        $taskWhereParam['task_id']=$taskid;

                        //先完成任务
                        $tmpModel['finish_time']=time();
                        $tmpModel['scope']=$task_scope;
                        M("PTaskPerson")->where($taskWhereParam)->save($tmpModel);

                        unset($taskWhereParam);
                        $taskWhereParam['id']=$taskid;
                        $tmpModel=M("PTask")->where($taskWhereParam)->find();

                        if($tmpModel){
                            $tmpModel['finish_count']+=1;
                            M("PTask")->where($taskWhereParam)->save($tmpModel);
                        }
                    }
                }

                $amount = trim($amount);

                if (empty($amount)) {//金额为空，不处理
                    if($task_scope>0){
                        $record['user_id'] = $user['id'];
                        $record['score'] = $task_scope;
                        $record['consume'] = $task_scope;
                        $record['expire_time']=time()+$expire2['value']*3600*24;

                        $record['add_time'] = time();
                        $record['type'] = 2;
                        $scoreRes = M("PScoreRecord")->add($record);
                        if(!$scoreRes){
                            $update = false;
                            break;
                        }
                    }
                    continue;
                }

                //$amount = str_replace(',', '', $amount);
                $amount = intval($amount);

                if ($amount <= 0) { //负增长，不处理
                    continue;
                }elseif ($amount < 10000){   //资金小于10000，不处理
                    continue;
                }elseif ($amount < 50000){  //5W以下加50积分
                    $score = 58;
                }elseif ($amount < 100000){
                    $score = 108;
                }else{
                    $score = 158;
                }

                $addData['lottery_time'] = array('exp', 'lottery_time+1');
                $res = $model->where(array('phone'=>$phone,'account'=>$account))->save($addData);
                if($res === false){
                    $update = false;
                    break;
                }

                $record['user_id'] = $user['id'];
                $record['score'] = ($score+$task_scope);
                $record['consume'] = $record['score'];
                $record['expire_time']=time()+$expire['value']*3600*24;

                $record['add_time'] = time();
                $record['type'] = 2;
                $scoreRes = M("PScoreRecord")->add($record);
                if(!$scoreRes){
                    $update = false;
                    break;
                }
            } 
            fclose($handle); //关闭指针 
            unlink($filename);
            
            if($update){
                $model->commit();
                $this->ajaxReturn(array('errcode'=>0, 'errmsg'=>'部分用户积分已变更，详情请查看积分记录！'));
            }else{
                $model->rollback();
                $this->ajaxReturn(array('errcode'=>10002, 'errmsg'=>'更新积分失败'));  
            }
        }else{
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'请上传文件'));
        }

    }


    public function amountview(){
        if(!empty($_FILES)){

            $filename='./Uploads/'.time();
            move_uploaded_file($_FILES["file"]["tmp_name"],$filename);

            $model = M("PUser");

            $expire=M('PConfig')->where(array('key'=>'import_expire'))->find();
            $list=array();

            $handle = fopen($filename, 'r');
            $first=true;
            $time=time();

            $records=D("PScoreRecord")->query('select user_id, consume from zsf_p_score_record where is_deleted=0 and consume>0 and expire_time>='.$time.' and type in (1,2,5,6,7)');


            while($data = fgetcsv($handle)){

                if(count($data) < 6){
                    continue;
                }
                $name = iconv('gb2312', 'utf-8', $data[0]);
                $name = trim($name);
                $phone = trim($data[1]);
                $account = trim($data[2]);
                $amount = $data[4];
                $taskid=$data[5];
                $task_scope=0;
                if (empty($name)) {
                    continue;
                }

                if($first){
                    $first=false;
                    continue;
                }

                $user = $model->where(array('phone'=>$phone,'account'=>$account))->find();
                if (!$user) {
                    continue;
                }

                if(!empty($taskid)){      //如果任务id不为空，则代表完成了任务
                    $tmpModel=M("PTaskPerson")->where(array('user_id'=>$user['id']))->find();

                    if($tmpModel && intval($tmpModel['finish_time'])<1){

                        //再添加任务的积分，
                        $task_scope=trim($data[6]);

                        $task_scope=intval($task_scope);

                    }
                }

                $amount = trim($amount);

                if (empty($amount)) {//金额为空，不处理
                    if($task_scope>0){
                        $sum=0;
                        foreach ($records as $k1 =>$v1){
                            if($v1['user_id']==$user['id']){
                                $sum+=$v1['consume'];
                            }
                        }
                        $user['score']=$sum;

                        $user['new_score']=$task_scope;
                        $user['updated_score']=$sum+$task_scope;
                        array_push($list,$user);

                    }
                    continue;
                }

                $amount = intval($amount);

                if ($amount <= 0) { //负增长，不处理
                    continue;
                }elseif ($amount < 10000){   //资金小于10000，不处理
                    continue;
                }elseif ($amount < 50000){  //5W以下加50积分
                    $score = 58;
                }elseif ($amount < 100000){
                    $score = 108;
                }else{
                    $score = 158;
                }
                $sum=0;
                foreach ($records as $k1 =>$v1){
                    if($v1['user_id']==$user['id']){
                        $sum+=$v1['consume'];
                    }
                }
                $user['score']=$sum;

                $user['new_score']=($score+$task_scope);
                $user['updated_score']=$sum+($score+$task_scope);
                array_push($list,$user);
            }
            fclose($handle); //关闭指针
            unlink($filename);

            $page = pagination(count($list), 10000 ,1);
            $array= array('data'=>$list, 'page'=>$page);

            return $this->ajaxReturn(array_merge($this->return, $array));

        }else{
            $page = pagination(0, 10000 ,1);
            $array= array('data'=>array(), 'page'=>$page);
            return $this->ajaxReturn(array_merge($this->return, $array));
        }

    }

    public function pictureupdate(){
        if(!empty($_FILES)){

            $filename='./Uploads/reg_banner.png';
            move_uploaded_file($_FILES["file"]["tmp_name"],$filename);


            $this->ajaxReturn(array('errcode'=>0, 'errmsg'=>'文件上传成功'));

        }else{

            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'请上传文件'));
        }
    }


}